package com.sip.stream.activity.preview;

import android.app.AlarmManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;
import android.util.Size;
import android.view.TextureView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sip.stream.ClientApp;
import com.sip.stream.R;
import com.sip.stream.activity.preview.model.CameraViewModel;
import com.sip.stream.activity.preview.model.FrontCameraRecordingViewModel;
import com.sip.stream.activity.preview.model.PreviewViewModel;
import com.sip.stream.activity.preview.model.SensorViewModel;
import com.sip.stream.activity.preview.model.ZFYStatusViewModel;
import com.sip.stream.databinding.IncludeStatusLayoutBinding;
import com.sip.stream.helper.PreviewSurfaceTextureHelper;
import com.sip.stream.media.ZFYCameraParameters;
import com.sip.stream.media.ZFYMediaManager;
import com.sip.stream.media.ZFYMediaStatus;
import com.sip.stream.rxbus.RxBus;
import com.sip.stream.utils.GBUtils;
import com.sip.stream.utils.ImageSaver;
import com.sip.stream.utils.zfy.ZFYMediaUtil;
import com.sip.stream.utils.zfy.voice.BeepTool;
import com.sip.stream.utils.zfy.voice.BeepType;
import com.sip.stream.utils.zfy.GSNV12OSDDataSource;
import com.sip.stream.utils.zfy.GSWAVDataSource;
import com.sip.stream.utils.zfy.IGSNV12DataSource;
import com.sip.stream.utils.zfy.IGSWAVDataSource;
import com.sip.stream.utils.zfy.PrevieDrawView;
import com.sip.stream.utils.zfy.PreviewDetectedBean;
import com.sip.stream.utils.zfy.RxBusTag;
import com.sip.stream.utils.zfy.ZFYCameraCallBack;
import com.sip.stream.utils.zfy.ZFYFilePath;
import com.sip.stream.utils.zfy.config.ZFYMediaConfig;
import com.sip.stream.utils.zfy.config.ZFYPlatformMediaConfig;
import com.sip.stream.utils.zfy.consumer.IGSMediaObserver;
import com.sip.stream.utils.zfy.event.ZFYMediaEvent;
import com.sip.stream.utils.zfy.proxy.PlatformProxy;
import com.sip.stream.utils.zfy.status.ZFYStatus;
import com.sip.stream.utils.zfy.yuv.GSYUVTool;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.BooleanSupplier;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class PreviewBusinessController implements DefaultLifecycleObserver {
    private static final String TAG = "PreviewBusiness";

    private static final long LONE_PRESS_TIME = 2000;
    public WeakReference<AppCompatActivity> activityWeakReference;
    private GSWAVDataSource audioRecord;
    private BehaviorSubject<Boolean> authFirstInitSubject;
    private TextureView cacheTextureView;
    private ZFYCameraCallBack cameraCallBack;
    private CameraViewModel cameraViewModel;
    private Disposable captureDisposable;
    private Disposable delayCloseWideAngleDisposable;
    private FrontCameraRecordingViewModel frontCameraRecordingViewModel;
    private boolean lastUseGLPreviewSurface;
    private RelativeLayout layoutPreview;
    private Disposable nextActionDisposable;
    private PrevieDrawView previeDrawView;
    private PreviewSurfaceTextureHelper previewSurfaceTextureHelper;
    private PreviewViewModel previewViewModel;
    private SensorViewModel sensorViewModel;
    private ZFYStatusViewModel statusViewModel;
    private TextureView textureView;
    private CompositeDisposable foregroundDisposable = new CompositeDisposable();
    private CompositeDisposable allDisposable = new CompositeDisposable();
    private AtomicBoolean isForeground = new AtomicBoolean();
    private AtomicBoolean isLeave = new AtomicBoolean(true);
    private boolean needRecordingTime = false;
    private boolean lastLongPass = false;
    private Disposable longPressDisposable = null;
    private AtomicBoolean leaveActionLock = new AtomicBoolean(false);
    private Queue<String> actionStack = new LinkedList();
    private Boolean resumeOrPauseStatus = Boolean.TRUE;

    //录制视频数据源
    private IGSNV12DataSource videoDataSource = null;
    //远程调度数据源
    private IGSNV12DataSource remoteVideoDataSource = null;
    //音频数据源
    private Disposable delayStopVideoActionDisposable = null;

    //视频录制数据源
    private IGSMediaObserver<IGSNV12DataSource> videoDataSourceObserver = new IGSMediaObserver() {
        @Override
        public  void onStop(Object obj) {

            Log.i(TAG, "videoDataSource onStop");
            videoDataSource = null;
            if (previewSurfaceTextureHelper != null) {
                previewSurfaceTextureHelper.setVideoDataSource(null);
            }
            if (isLeave.get()) {
                return;
            }
            updateCameraStream(isForeground.get(), ZFYMediaManager.getInstance().isNeedVideoStream(), ZFYMediaManager.getInstance().isNeedRemoteStream());
        }
    };

    //远程调度数据源
    private IGSMediaObserver<IGSNV12DataSource> remoteVideoDataSourceObserver = new IGSMediaObserver() {
        @Override
        public  void onStop(Object obj) {
            Log.i(TAG, "remotevideoDataSource onStop");
            remoteVideoDataSource = null;
            if (previewSurfaceTextureHelper != null) {
                previewSurfaceTextureHelper.setRemoteVideoDataSource(null);
            }
            updateCameraStream(true, ZFYMediaManager.getInstance().isNeedVideoStream(), ZFYMediaManager.getInstance().isNeedRemoteStream());
        }
    };

    //音频数据源
    private IGSMediaObserver<IGSWAVDataSource> audioDataSourceObserver = new IGSMediaObserver<IGSWAVDataSource>() {
        @Override
        public void onStop(IGSWAVDataSource iGSWAVDataSource) {
            if (audioRecord != null) {
                Log.i(TAG, "stopRecord");
                audioRecord.stopRecord();
                audioRecord = null;
            }
        }
    };



    public static  Boolean lambda$updateCameraStream$72(Boolean bool, Boolean bool2) throws Exception {
        return bool;
    }

    public PreviewBusinessController(AppCompatActivity appCompatActivity) {
        setUp(appCompatActivity);
    }

    public void setUp(AppCompatActivity appCompatActivity) {
        this.activityWeakReference = new WeakReference<>(appCompatActivity);
        this.previewViewModel = new PreviewViewModel(appCompatActivity);
        this.frontCameraRecordingViewModel = new FrontCameraRecordingViewModel(appCompatActivity);
    }

    private SensorViewModel getSensorViewModel() {
        if (this.sensorViewModel == null) {
            SensorViewModel sensorViewModel = new SensorViewModel(getContext());
            this.sensorViewModel = sensorViewModel;
            sensorViewModel.setListener(new SensorViewModel.SensorViewModelListener() {
                @Override
                public  void onSensorEvent(int i) {
                    PreviewBusinessController.this.m589x1acb97a9(i);
                }
            });
        }
        return this.sensorViewModel;
    }

    public  void m589x1acb97a9(int i) {
        if (i == 1) {
            handleMediaAction(ZFYMediaManager.KNOCK_PROTECT);
        } else if (i != 2) {
        } else {
            handleMediaAction(ZFYMediaManager.VIDEO_PROTECT);
        }
    }

    public PreviewViewModel getViewObserver() {
        return this.previewViewModel;
    }

    public Context getContext() {
        return this.activityWeakReference.get();
    }

    public void setUpStatus(IncludeStatusLayoutBinding includeStatusLayoutBinding) {
        ZFYStatusViewModel zFYStatusViewModel = new ZFYStatusViewModel(includeStatusLayoutBinding, getContext());
        this.statusViewModel = zFYStatusViewModel;
        zFYStatusViewModel.setUpStatus();
    }

    public void setUpTextureView(RelativeLayout relativeLayout, TextureView textureView, PrevieDrawView previeDrawView) {
        this.layoutPreview = relativeLayout;
        this.previeDrawView = previeDrawView;
        this.textureView = textureView;
    }

    public void setUpFrontTextureView(RelativeLayout relativeLayout) {
        this.frontCameraRecordingViewModel.setUpTextureView(relativeLayout);
    }

    public CameraViewModel getCameraViewModel() {
        if (this.cameraViewModel == null) {
            if (this.cameraCallBack == null) {
                this.cameraCallBack = new ZFYCameraCallBack() {
                    @Override
                    public void onCameraSwitch() {
                        PreviewBusinessController.this.onCameraSwitch();
                    }

                    @Override
                    public void onError(String str) {
                        Log.e(TAG, "onError " + str);
                    }

                    @Override
                    public void onVideoStream(byte[] bArr, long j) {
                        if (PreviewBusinessController.this.videoDataSource != null) {
                            PreviewBusinessController.this.videoDataSource.addNV12Data(bArr, j);
                        } else {
                            Log.w(TAG, "videoDataSource == null");
                        }
                    }

                    @Override
                    public void onRemoteStream(byte[] bArr, long j) {
                        if (PreviewBusinessController.this.remoteVideoDataSource != null) {
                            PreviewBusinessController.this.remoteVideoDataSource.addNV12Data(bArr, j);
                        }
                    }

                    @Override
                    public void onCaptureComplete(byte[] bArr, int i) {
                        ZFYMediaManager.getInstance().onCaptureComplete(bArr, i, PreviewBusinessController.this.getCameraViewModel().getCameraParameters().getCaptrueWidth(), PreviewBusinessController.this.getCameraViewModel().getCameraParameters().getCaptrueHeight());
                    }

                    @Override
                    public SurfaceTexture getPreviewSurfaceTexture() {
                        return PreviewBusinessController.this.getPreviewSurfaceTexture();
                    }

                    @Override
                    public void cameraStatusChange(int i) {
                        Log.w(TAG, "cameraStatusChange " + i);
                        PreviewBusinessController.this.onCameraStatuChange();
                    }
                };
            }
            CameraViewModel cameraViewModel = new CameraViewModel(getContext(), this.cameraCallBack);
            this.cameraViewModel = cameraViewModel;
            cameraViewModel.setFront(ZFYMediaManager.getInstance().getConfig().isFrontCameraVideo());
        }
        return this.cameraViewModel;
    }

    private void refreshStorageSize() {
        if (ZFYFilePath.getInstance().checkCardStatus()) {
            this.previewViewModel.setTvStorage(ZFYFilePath.getInstance().getEmptyGB() + "G");
            this.previewViewModel.setTvStorageColor(-1);
            return;
        }
        this.previewViewModel.setTvStorage("- G");
        this.previewViewModel.setTvStorageColor(getColor(R.color.red_zfy));
    }

    private void subscribeForeground() {
        RxBus.getDefault().subscribe(this, RxBusTag.LOCANTION_CHANGE, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String str) {
                PreviewBusinessController.this.previewViewModel.setGPSStr(String.format("%s:%.6f\n%s:%.6f", ZFYStatus.getInstance().getLocation().getLatitudeStr(), Double.valueOf(ZFYStatus.getInstance().getLocation().getLatitude()), ZFYStatus.getInstance().getLocation().getLongitudeStr(), Double.valueOf(ZFYStatus.getInstance().getLocation().getLongitude())));
            }
        });
        RxBus.getDefault().subscribe(this, RxBusTag.CHANGEUSER_EVENT, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String str) {
                PreviewBusinessController.this.refreshStaticData();
            }
        });
        this.previewViewModel.setGPSStr(String.format("%s:%.6f\n%s:%.6f", ZFYStatus.getInstance().getLocation().getLatitudeStr(), Double.valueOf(ZFYStatus.getInstance().getLocation().getLatitude()), ZFYStatus.getInstance().getLocation().getLongitudeStr(), Double.valueOf(ZFYStatus.getInstance().getLocation().getLongitude())));
        RxBus.getDefault().subscribe(this, RxBusTag.PLATFORM_CONTECT, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String str) {
                Log.i(TAG, RxBusTag.PLATFORM_CONTECT + str);
                PreviewBusinessController.this.previewViewModel.refreshStaticData();
            }
        });
        RxBus.getDefault().subscribe(this, RxBusTag.AI_DETECTED_EVENT, new RxBus.Callback<PreviewDetectedBean>() {
            @Override
            public void onEvent(PreviewDetectedBean previewDetectedBean) {
                if (PreviewBusinessController.this.isForeground.get()) {
                    PreviewBusinessController.this.previewViewModel.getDetectedBeanBehaviorSubject().onNext(previewDetectedBean);
                }
            }
        });
    }

    private void subscribeRxBus() {
        Log.i(TAG, "subscribeRxBus unregister");
        RxBus.getDefault().unregister(this);
        subscribeForeground();
        Log.i(TAG, "subscribeRxBus");
        RxBus.getDefault().subscribe(this, RxBusTag.MEDIA_EVENT, new AnonymousClass6());
    }

    public class AnonymousClass6 extends RxBus.Callback<ZFYMediaEvent> {
        AnonymousClass6() {
        }

        @Override
        public void onEvent(ZFYMediaEvent zFYMediaEvent) {
            Log.i(TAG, "RxBus: " + zFYMediaEvent.getType() + " " + Process.myTid());
            String type = zFYMediaEvent.getType();
            type.hashCode();
            char c = 65535;
            switch (type.hashCode()) {
                case -1601921652:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_CHECK_AUDIO_COMMUNICATION_MODE)) {
                        c = 0;
                        break;
                    }
                    break;
                case -1522291173:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_TIP)) {
                        c = 1;
                        break;
                    }
                    break;
                case -305405768:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_KEEP_SCREEN_ON)) {
                        c = 2;
                        break;
                    }
                    break;
                case -133735226:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_PPI_CHANGE)) {
                        c = 3;
                        break;
                    }
                    break;
                case -103026676:
                    if (type.equals("EVENT_TYPE_STORAGE_ABNORMAL")) {
                        c = 4;
                        break;
                    }
                    break;
                case 651032100:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_STOP_ALL)) {
                        c = 5;
                        break;
                    }
                    break;
                case 1064560789:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_MOVE_DECTECTED)) {
                        c = 6;
                        break;
                    }
                    break;
                case 1195594692:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_NOT_KEEP_SCREEN_ON)) {
                        c = 7;
                        break;
                    }
                    break;
                case 1648450440:
                    if (type.equals("EVENT_TYPE_ERROR")) {
                        c = '\b';
                        break;
                    }
                    break;
                case 1780580437:
                    if (type.equals(ZFYMediaEvent.EVENT_TYPE_CHANGE_MEDIA_CONFIG_FROM_PLATFORM)) {
                        c = '\t';
                        break;
                    }
                    break;
            }
            switch (c) {
                case 0:
                    PreviewBusinessController.this.handleMediaAction(ZFYMediaManager.ACTION_CHECK_AUDIO_MODE);
                    return;
                case 1:
                    if (zFYMediaEvent.getMessageRes() <= 0) {
                        PreviewBusinessController.this.showToast(zFYMediaEvent.getValue());
                        return;
                    }
                    PreviewBusinessController previewBusinessController = PreviewBusinessController.this;
                    previewBusinessController.showToast(previewBusinessController.getString(zFYMediaEvent.getMessageRes()));
                    return;
                case 2:
                    Single.just(Boolean.TRUE).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer() {
                        @Override
                        public void accept(Object obj) {
                            PreviewBusinessController.this.activityWeakReference.get().getWindow().addFlags(128);
                        }
                    });
                    return;
                case 3:
                    PreviewBusinessController.this.doAfterChangePPI();
                    return;
                case 4:
                    PreviewBusinessController previewBusinessController2 = PreviewBusinessController.this;
                    ToastUtils.showShort(ClientApp.clientApp.getText(R.string.error_storage_abnormal));
                    return;
                case 5:
                    //PreviewBusinessController.this.intallPackage();
                    return;
                case 6:
                    PreviewBusinessController.this.handleMediaAction(ZFYMediaManager.ACTION_VIDEO_START);
                    return;
                case 7:
                    Single.just(Boolean.TRUE).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer() {
                        @Override
                        public  void accept(Object obj) {
                            PreviewBusinessController.this.activityWeakReference.get().getWindow().clearFlags(128);
                        }
                    });
                    return;
                case '\b':
                    if (zFYMediaEvent.getMessageRes() <= 0) {
                        PreviewBusinessController.this.showToast(zFYMediaEvent.getValue());
                        return;
                    }
                    PreviewBusinessController previewBusinessController3 = PreviewBusinessController.this;
                    previewBusinessController3.showToast(previewBusinessController3.getString(zFYMediaEvent.getMessageRes()));
                    return;
                case '\t':
                    PreviewBusinessController.this.handleMediaAction(ZFYMediaManager.ACTION_CHANGE_MEDIA_CONFIG_FROM_PLATFORM);
                    return;
                default:
                    return;
            }
        }
    }


    private Single<Boolean> changeMediaConfig() {
        return pauseCameraAndSurface().delay(500L, TimeUnit.MILLISECONDS).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return resumeCamera();
            }
        }).doAfterSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                if (ZFYMediaManager.getInstance().getStatus().isRemoteVideoAndAudio()) {
                    PlatformProxy.getInstance().stopStreaming();
                }
                if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
                    handleMediaAction(ZFYMediaManager.ACTION_VIDEO_STOP);
                    handleMediaAction(ZFYMediaManager.ACTION_VIDEO_START);
                }
            }
        });
    }

    private Single<Boolean> resetPPIAction() {
        Single just;
        Single just2;
        Log.i(TAG, "resetPPIAction " + ZFYMediaManager.getInstance().getStatus().getLastStreamHeight());
        if (ZFYMediaManager.getInstance().getCameraParameters().getVideoHeight() == 1080 || ZFYMediaManager.getInstance().getStatus().getLastStreamHeight() < 0) {
            return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    Log.i(TAG, "resetPPIAction not need resetPPI");
                    ZFYMediaManager.getInstance().getStatus().setLastStreamHeight(-1);
                }
            });
        }

        if (ZFYMediaManager.getInstance().getStatus().isVideoStart())
        {
            Log.i(TAG, "forceChangeMediaConfig isVideoStart");
            just = Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
                @Override
                public void accept(Object obj) {
                    handleMediaAction(ZFYMediaManager.ACTION_VIDEO_STOP);
                }
            });
            just2 = Single.just(Boolean.TRUE).delay(1L, TimeUnit.SECONDS).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    handleMediaAction(ZFYMediaManager.ACTION_VIDEO_START);
                }
            });
        } else {
            just = Single.just(Boolean.TRUE);
            just2 = Single.just(Boolean.TRUE);
        }
        return just.doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                ZFYMediaConfig config = ZFYMediaManager.getInstance().getConfig();
                Size size = new Size(1920, 1080);
                GBUtils.setPreViewStreamPPI(size.getWidth() + ZFYMediaUtil.SEP_PPI + size.getHeight(),config);
                int resetStreamBitRate = config.getResetStreamBitRate();
                if (resetStreamBitRate < 512) {
                    resetStreamBitRate = 512;
                }
                config.setStreamBitRate(resetStreamBitRate);
                ZFYMediaManager.getInstance().saveConfig(config);
                ZFYMediaManager.getInstance().getStatus().setLastStreamHeight(-1);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return pauseCameraAndSurface();
            }
        }).delay(500L, TimeUnit.MILLISECONDS).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return resumeCamera();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return updateCameraStream();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return Single.just(true);
            }
        });
    }


    private Single<Boolean> changePPIAction() {
        Log.i(TAG, "changePPIAction");
        return switchPPIMediaConfig().flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return pauseCameraAndSurface();
            }
        }).delay(500L, TimeUnit.MILLISECONDS).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return resumeCamera();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                String format = String.format(getString(R.string.preview_switch_ppi), Integer.valueOf(ZFYMediaManager.getInstance().getConfig().getVideoHeight()));
                showToast(format);
                BeepTool.playString(format);
            }
        });
    }

    private Single<Boolean> switchPPIMediaConfig() {
        return Single.just(Boolean.TRUE);
    }

    public void doAfterChangePPI() {
        ZFYCameraParameters cameraParameters = ZFYMediaManager.getInstance().getCameraParameters();
        Log.i(TAG, "parameters " + cameraParameters.getVideoHeight());
        this.previewSurfaceTextureHelper.setDefaultBufferSize(cameraParameters.getVideoWidth(), cameraParameters.getVideoHeight());
        this.previewViewModel.setPpiStr(cameraParameters.getVideoHeight() + "P");
        if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
            handleMediaAction(ZFYMediaManager.ACTION_VIDEO_STOP);
            handleMediaAction(ZFYMediaManager.ACTION_VIDEO_START);
        }
    }

    @Override
    public void onStart(LifecycleOwner lifecycleOwner) {
        Log.d(TAG, "onStart " + this);
    }

    @Override
    public void onResume(LifecycleOwner lifecycleOwner) {
        Log.d(TAG, "onResume " + this);
        this.isForeground.set(true);
        handleMediaAction(ZFYMediaManager.START_PREVIEW);
    }

    @Override
    public void onPause(LifecycleOwner lifecycleOwner) {
        Log.w(TAG, "onPause" + this + " isScreenOn " + ZFYStatus.getInstance().isScreenOn());
        this.isForeground.set(false);
    }

    @Override
    public void onStop(LifecycleOwner lifecycleOwner) {
        this.isForeground.set(false);
        Log.w(TAG, "onStop" + this + " isScreenOn " + ZFYStatus.getInstance().isScreenOn());
        handleMediaAction(ZFYMediaManager.PAUSE_PREVIEW);
    }

    @Override
    public void onDestroy(LifecycleOwner lifecycleOwner) {
        Log.i(TAG, "onDestroy ???");
        ZFYMediaManager.getInstance().setVideoDataSource(this.videoDataSource);
        ZFYMediaManager.getInstance().setRemoteVideoDataSource(this.remoteVideoDataSource);
        RxBus.getDefault().unregister(this);
        CameraViewModel cameraViewModel = this.cameraViewModel;
        if (cameraViewModel != null) {
            cameraViewModel.release();
            this.cameraViewModel = null;
        }
    }

    public String getLastString() {
        if (!this.needRecordingTime) {
            return this.previewViewModel.getStatusString();
        }
        Date beginRecordingDate = ZFYMediaManager.getInstance().getStatus().getBeginRecordingDate();
        if (beginRecordingDate == null) {
            Log.w(TAG, "date == null");
            return "";
        }
        long currentTimeMillis = (System.currentTimeMillis() - beginRecordingDate.getTime()) / 1000;
        if (currentTimeMillis < 0) {
            ZFYMediaManager.getInstance().getStatus().setBeginRecordingDate(new Date());
            Log.w(TAG, "astTime < 0");
            return "";
        }
        return String.format("%02d:%02d:%02d", Integer.valueOf((int) (currentTimeMillis / 3600)), Integer.valueOf((int) ((currentTimeMillis / 60) % 60)), Integer.valueOf((int) (currentTimeMillis % 60)));
    }

    public String getString(int i) {
        return getContext().getString(i);
    }

    private int getColor(int i) {
        return getContext().getResources().getColor(i);
    }

    public void onKeyEvent(int i, boolean z) {
        if (z) {
            Disposable disposable = this.longPressDisposable;
            if (disposable != null) {
                disposable.dispose();
                this.longPressDisposable = null;
            }
            if (!this.lastLongPass) {
                onKeyEventAction(i, false);
            }
            this.lastLongPass = false;
        } else if (this.longPressDisposable != null) {
        } else {
            Single.just(Integer.valueOf(i)).delay(LONE_PRESS_TIME, TimeUnit.MILLISECONDS).doFinally(new Action() {
                @Override
                public  void run() {
                    PreviewBusinessController.this.longPressDisposable = null;
                }
            }).subscribe(new SingleObserver<Integer>() {
                @Override
                public void onSubscribe(Disposable disposable2) {
                    PreviewBusinessController.this.longPressDisposable = disposable2;
                }

                @Override
                public void onSuccess(Integer num) {
                    PreviewBusinessController.this.lastLongPass = true;
                    Log.i(TAG, "onKeyEventAction lastLongPass " + PreviewBusinessController.this.lastLongPass);
                    PreviewBusinessController.this.onKeyEventAction(num.intValue(), true);
                }

                @Override
                public void onError(Throwable th) {
                    th.printStackTrace();
                }
            });
        }
    }

    public void onKeyEventAction(int i, boolean z) {
        Log.d(TAG, "onKeyEventAction " + i + " isLongPress  " + z);
        if (ZFYStatus.getInstance().isLocked())
        {
            if (!z || i != 132) {
                showToast(getString(R.string.meida_error_locked));
            } else {
                onMarkEvent(true);
            }
        } else if (i == 135) {
            Log.i(TAG, "onClickVideo");
        } else if (i == 134) {
            Log.i(TAG, "onClickAudio");
        } else if (i == 131) {
            Log.i(TAG, "onClickCamera");
        }
    }

    public void showToast(String str) {
        if (StringUtils.isEmpty(str)) {
            return;
        }
        this.previewViewModel.showToast(str);
    }

    public Single<Boolean> leaveAction() {
        Log.w(TAG, "leaveActionLock " + this.leaveActionLock.get() + " isLeave " + this.isLeave.get());
        if (this.leaveActionLock.get() || this.isLeave.get()) {
            CameraViewModel cameraViewModel = this.cameraViewModel;
            if (cameraViewModel == null || !cameraViewModel.isOpenedCamera()) {
                return Single.just(Boolean.TRUE);
            }
            return Single.error(new Exception(getString(R.string.action_to_fast)));
        }
        this.leaveActionLock.set(true);
        Single.timer(3L, TimeUnit.SECONDS).subscribe(new SingleObserver<Long>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Long l) {
                PreviewBusinessController.this.leaveActionLock.set(false);
            }
        });
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                PreviewBusinessController.this.isLeave.set(true);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return stopPreVideoAction();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getSensorViewModel().release();
                ZFYMediaManager.getInstance().onLeavePreview();
                if (audioRecord != null) {
                    audioRecord.stopRecord();
                    audioRecord = null;
                }
                Log.i(TAG, "leaveAction RxBus unregister");
                RxBus.getDefault().unregister(this);
                cameraViewModel.leaveAction();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return pauseCameraAndSurface();
            }
        }).doFinally(new Action() {
            @Override
            public  void run() {
                leaveActionLock.set(false);
                if (videoDataSource != null) {
                    Log.e(TAG, "videoDataSource != null");
                    videoDataSource = null;
                }
            }
        });
    }


    private Single<Boolean> pauseCameraAndSurface() {
        return this.cameraViewModel.onPauseAction().onErrorReturnItem(Boolean.TRUE).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return releaseSurface();
            }
        });
    }


    private synchronized Single<Boolean> releaseSurface() {
        if (this.previewSurfaceTextureHelper == null) {
            Log.w(TAG, "releaseSurface previewSurfaceTextureHelper == null");
            return Single.just(Boolean.TRUE);
        }
        Log.d(TAG, "releaseSurface");
        return Single.just(Boolean.TRUE).observeOn(AndroidSchedulers.mainThread()).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
            }
        }).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return previewSurfaceTextureHelper.releaseSurface();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                previewSurfaceTextureHelper = null;
            }
        });
    }


    public SurfaceTexture getPreviewSurfaceTexture() {
        return this.previewSurfaceTextureHelper.getPreviewSurface();
    }

    private Single<TextureView> addTextureView() {
        return Single.just(Boolean.TRUE).observeOn(AndroidSchedulers.mainThread()).map(new Function() {
            @Override
            public Object apply(Object obj) {
                if (cacheTextureView != null) {
                    return cacheTextureView;
                }
                TextureView textureView = new TextureView(layoutPreview.getContext());
                textureView.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
                layoutPreview.addView(textureView);
                Log.i(TAG, "add View success");
                cacheTextureView = textureView;
                return textureView;
            }
        });
    }

    private Single<Boolean> setUpSurface() {
        if (this.previewSurfaceTextureHelper != null) {
            Log.i(TAG, "previewSurfaceTextureHelper != null");
            return this.previewSurfaceTextureHelper.setUpSurface();
        }
        return addTextureView().flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                TextureView textureView = (TextureView) obj;
                Log.i(TAG, "use PreviewSurfaceTextureHelper");
                previewSurfaceTextureHelper = new PreviewSurfaceTextureHelper(textureView);
                lastUseGLPreviewSurface = false;
                previewSurfaceTextureHelper.setVideoDataSource(videoDataSource);
                previewSurfaceTextureHelper.setRemoteVideoDataSource(remoteVideoDataSource);
                return previewSurfaceTextureHelper.setUpSurface().doOnSuccess(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean bool) throws Exception {
                        Log.d(PreviewBusinessController.TAG, "setUpSurface doOnSuccess");
                    }
                });
            }
        });
    }

    public void onCameraSwitch() {
        Log.i(TAG, "onCameraSwitch");
        Single.just(Boolean.FALSE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                ZFYMediaManager.getInstance().forceStop();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return releaseSurface();
            }
        }).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return setUpSurface();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                Log.i(TAG, "setUpSurface success");
            }
        }).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return getCameraViewModel().setUpCamera();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                ZFYCameraParameters zFYCameraParameters = (ZFYCameraParameters) obj;
                Log.i(TAG, "setUpCamera success");
               previewSurfaceTextureHelper.doAfterCameraOpened();
                ZFYMediaManager.getInstance().getCameraParameters().deepCopy(zFYCameraParameters);
                if (previeDrawView != null) {
                    previeDrawView.setPreviewWidth(zFYCameraParameters.getVideoWidth());
                }
                previewViewModel.setPpiStr(zFYCameraParameters.getVideoHeight() + "P");
                previewViewModel.setZoomPersent(Float.valueOf(0.0f));
            }
        }).subscribeOn(Schedulers.single()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleObserver<ZFYCameraParameters>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                PreviewBusinessController.this.allDisposable.add(disposable);
            }

            @Override
            public void onSuccess(ZFYCameraParameters zFYCameraParameters) {
                PreviewBusinessController.this.previewSurfaceTextureHelper.setDefaultBufferSize(zFYCameraParameters.getVideoWidth(), zFYCameraParameters.getVideoHeight());
                PreviewBusinessController.this.startCameraPreview();
                PreviewBusinessController previewBusinessController = PreviewBusinessController.this;
                previewBusinessController.showToast(String.format(previewBusinessController.getString(R.string.preview_camera_switch_tip), PreviewBusinessController.this.getCameraViewModel().getLocalizedName()));
            }

            @Override
            public void onError(Throwable th) {
                th.printStackTrace();
                PreviewBusinessController.this.showToast(th.getMessage());
            }
        });
    }


    public void onCameraStatuChange() {
        ZFYCameraParameters cameraParameters = ZFYMediaManager.getInstance().getCameraParameters();
        CameraViewModel cameraViewModel = this.cameraViewModel;
        if (cameraViewModel != null) {
            if (cameraViewModel.isInfraredLightOpen()) {
                this.previewViewModel.setPpiStr(getString(R.string.preview_night_mode));
            } else {
                this.previewViewModel.setPpiStr(cameraParameters.getVideoHeight() + "P");
            }
        }
        this.previewViewModel.setZoomPersent(Float.valueOf(0.0f));
        PlatformProxy.getInstance().syncPlatformMediaConfig(new ZFYPlatformMediaConfig(ZFYMediaManager.getInstance().getConfig(), ZFYMediaManager.getInstance().getStatus()));
        this.previewViewModel.refreshRecordingAction();
    }

    public void startCameraPreview() {
        Log.i(TAG, "startCameraPreview");
        updateCameraStream(true, ZFYMediaManager.getInstance().isNeedVideoStream(), ZFYMediaManager.getInstance().isNeedRemoteStream());
        handleMediaAction(ZFYMediaManager.ACTION_AI_PREVIEW, false);
        String stickyAction = ZFYMediaManager.getInstance().getStickyAction();
        Log.i(TAG, "stickyAction: " + stickyAction);
        char c = 1;
        int i = 0;
        if (stickyAction.equals(ZFYMediaManager.ACTION_REMOTE_AUDIO)){
            c = 0;
        }else if (stickyAction.equals(ZFYMediaManager.ACTION_AUDIO)) {
            c = 2;
        }else if (stickyAction.equals(ZFYMediaManager.ACTION_AUDIO_STOP)){
            c = 3;
        }else{
            ZFYMediaManager.getInstance().setStickyAction(null);
        }
        switch (c) {
            case 0:
            case 1:
            case 2:
            case 3:
                break;
            default:
                i = 1500;
                break;
        }
        ZFYMediaManager.getInstance().setStickyAction(null);
        Single.just("").delay(i, TimeUnit.MILLISECONDS).subscribe(new SingleObserver<String>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(String str2) {
                Log.i(TAG, "startCameraPreview nextAction");
                PreviewBusinessController.this.nextAction();
            }
        });
    }

    public void refreshStaticData() {
        this.previewViewModel.refreshStaticData();
    }

    private Single<Boolean> firstInstall() {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(TAG, 0);
        if (sharedPreferences.getBoolean("firstInstall", true)) {
            sharedPreferences.edit().putBoolean("firstInstall", false).commit();
            return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    showToast(getContext().getString(R.string.firstinstall_tip));
                }
            }).delay(2L, TimeUnit.SECONDS).flatMap(new Function() {
                @Override
                public  Object apply(Object obj) {
                    return resetSystem();
                }
            }).delay(1L, TimeUnit.SECONDS).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    System.exit(0);
                }
            });
        }
        return Single.just(Boolean.TRUE);
    }

    private Single<Boolean> authFirstInit() {
        Single<Boolean> just = null;
        Log.i(TAG, "not isFirstInit");
        if (just == null) {
            just = Single.just(Boolean.TRUE);
        }
        return just.doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                Log.i(TAG, "setFirstInit success");
                ZFYStatus.getInstance().setDeviceLocked(false);
                authFirstInitSubject = null;
                if (ZFYMediaManager.getInstance().getConfig().isBootRecord()) {
                    Log.i(TAG, "isBootRecord");
                    Single.just(Boolean.TRUE).delay(2L, TimeUnit.SECONDS).subscribe(new SingleObserver<Boolean>() {
                        @Override
                        public void onError(Throwable th) {
                        }

                        @Override
                        public void onSubscribe(Disposable disposable) {
                        }

                        @Override
                        public void onSuccess(Boolean bool2) {
                            PreviewBusinessController.this.handleMediaAction(ZFYMediaManager.ACTION_VIDEO);
                        }
                    });
                }
            }
        });
    }


    private Single<Boolean> resumeCamera() {
        if (getCameraViewModel().isOpenedCamera()) {
            return Single.just(Boolean.TRUE);
        }
        Log.i(TAG, "resumeCamera");
        return Single.just(Boolean.TRUE).observeOn(Schedulers.single()).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getCameraViewModel().setUserPreviewSurface(false);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return getCameraViewModel().setUpCamera();
            }
        }).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                ZFYCameraParameters zFYCameraParameters = (ZFYCameraParameters) obj;

                ZFYMediaManager.getInstance().getCameraParameters().deepCopy(zFYCameraParameters);
                if (previeDrawView != null) {
                    previeDrawView.setPreviewWidth(zFYCameraParameters.getVideoWidth());
                }
                previewViewModel.setPpiStr(zFYCameraParameters.getVideoHeight() + "P");
                previewViewModel.setZoomPersent(Float.valueOf(0.0f));
                return Boolean.TRUE;
            }
        });
    }



    public void onMarkEvent(boolean z) {
        Log.i(TAG, "onMarkEvent isLongPress " + z);
        if (z) {
            switchLocked();
        } else if (ZFYStatus.getInstance().isLocked()) {
            showToast(getString(R.string.meida_error_locked));
        } else if (ZFYMediaManager.getInstance().getStatus().isAudioStart() || ZFYMediaManager.getInstance().getStatus().isVideoStart() || ZFYMediaManager.getInstance().getStatus().isDelayRecording()) {
            ZFYMediaManager.getInstance().switchMarkRecording();
        }
    }

    private void switchLocked() {
        if (ZFYMediaManager.getInstance().getStatus().isAudioStart() || ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
            ZFYStatus.getInstance().setLocked(!ZFYStatus.getInstance().isLocked());
            if (ZFYStatus.getInstance().isLocked()) {
                showToast(getString(R.string.meida_locked));
                BeepTool.play(BeepType.START, ClientApp.clientApp.getResources().getString(R.string.meida_locked));
            } else {
                showToast(getString(R.string.meida_unlocked));
                BeepTool.play(BeepType.STOP, getString(R.string.meida_unlocked));
            }
        }
        RxBus.getDefault().post("", "ZFYStatusEvent");
    }

    private Single<Boolean> captureWithConfig() {
        Disposable disposable = this.captureDisposable;
        if (disposable != null) {
            disposable.dispose();
            this.captureDisposable = null;
        }
        ZFYMediaConfig config = ZFYMediaManager.getInstance().getConfig();
        if (config.getCaptureMutiCount() > 1) {
            ZFYMediaManager.getInstance().getStatus().setMutiCaptureTime(config.getCaptureMutiCount() - 1);
            Single<Boolean> capture = capture();
            Observable.just(Boolean.TRUE).delay(ZFYMediaManager.getInstance().getConfig().getCaptureMutiSepTime(), TimeUnit.SECONDS).map(new Function() {
                @Override
                public  Object apply(Object obj) {
                    return PreviewBusinessController.this.m563xb853ccd9((Boolean) obj);
                }
            }).repeatUntil(new BooleanSupplier() {
                @Override
                public  boolean getAsBoolean() {
                    return PreviewBusinessController.lambda$captureWithConfig$51();
                }
            }).subscribe(new Observer<Boolean>() {
                @Override
                public void onComplete() {
                }

                @Override
                public void onError(Throwable th) {
                }

                @Override
                public void onNext(Boolean bool) {
                }

                @Override
                public void onSubscribe(Disposable disposable2) {
                    PreviewBusinessController.this.captureDisposable = disposable2;
                }
            });
            return capture;
        } else if (config.getCaptureDelay() > 0) {
            showToast(String.format(getString(R.string.media_capture_delay), Integer.valueOf(config.getCaptureDelay())));
            Single.just(Boolean.TRUE).delay(config.getCaptureDelay(), TimeUnit.SECONDS).subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onSubscribe(Disposable disposable2) {
                    PreviewBusinessController.this.captureDisposable = disposable2;
                }

                @Override
                public void onSuccess(Boolean bool) {
                    ZFYMediaManager.getInstance().handlerActionWithCheckForground(PreviewBusinessController.this.getContext(), ZFYMediaManager.ACTION_CAPTRUE);
                }

                @Override
                public void onError(Throwable th) {
                    th.printStackTrace();
                }
            });
            return Single.just(Boolean.TRUE);
        } else {
            return capture();
        }
    }

    public  Boolean m563xb853ccd9(Boolean bool) {
        ZFYMediaManager.getInstance().handlerActionWithCheckForground(getContext(), ZFYMediaManager.ACTION_CAPTRUE);
        return Boolean.TRUE;
    }

    public static  boolean lambda$captureWithConfig$51(){
        int mutiCaptureTime = ZFYMediaManager.getInstance().getStatus().getMutiCaptureTime();
        int i = mutiCaptureTime - 1;
        Log.i(TAG, "now " + mutiCaptureTime + " after " + i);
        ZFYMediaManager.getInstance().getStatus().setMutiCaptureTime(i);
        return i < 1;
    }

    private Single<Boolean> capture() {
        SingleSource delay;
        if (!ZFYMediaManager.getInstance().checkDeviceStatus()) {
            return Single.just(Boolean.TRUE);
        }
        if (this.videoDataSource != null) {
            delay = this.videoDataSource.capture().observeOn(Schedulers.newThread()).map(new Function() {
                @Override
                public Object apply(Object obj) {
                    int width = videoDataSource.getWidth();
                    int height = videoDataSource.getHeight();
                    return Boolean.valueOf(new ImageSaver().saveImage(GSYUVTool.copyNV12ToNV21((byte[]) obj, width, height), width, height) != null);
                }
            });
        } else {
            if (this.remoteVideoDataSource != null) {
                delay = this.remoteVideoDataSource.capture().observeOn(Schedulers.newThread()).map(new Function() {
                    @Override
                    public Object apply(Object obj) {
                        int width = remoteVideoDataSource.getWidth();
                        int height = remoteVideoDataSource.getHeight();
                        return Boolean.valueOf(new ImageSaver().saveImage(GSYUVTool.copyNV12ToNV21((byte[]) obj, width, height), width, height) != null);
                    }
                });
            } else {
                delay = Single.create(new SingleOnSubscribe() {
                    @Override
                    public void subscribe(SingleEmitter singleEmitter) {
                        ZFYMediaManager.getInstance().startCapture(singleEmitter);
                        getCameraViewModel().capture();
                    }
                }).doOnSubscribe(new Consumer() {
                    @Override
                    public void accept(Object obj) {
                        BeepTool.play(BeepType.CAPTURED);
                    }
                }).delay(500L, TimeUnit.MILLISECONDS);
            }
        }
        return Single.zip(ZFYMediaManager.getInstance().checkCanStartMedia(), delay, new BiFunction() {
            @Override
            public Object apply(Object obj, Object obj2) {
                return Boolean.TRUE;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                if (ZFYMediaManager.getInstance().getStatus().getMutiCaptureTime() > 0) {
                    showToast(String.format(getString(R.string.meida_muti_capture_save_complete), Integer.valueOf(ZFYMediaManager.getInstance().getStatus().getMutiCaptureTime())));
                } else {
                    showToast(getString(R.string.meida_capture_save_complete));
                }
            }
        });
    }


    public void handleMediaAction(String action) {
        handleMediaAction(action, true);
    }

    public void handleMediaAction(String str, boolean z) {
        str.hashCode();
        char c = 65535;
        switch (str.hashCode()) {
            case 93166550:
                if (str.equals(ZFYMediaManager.ACTION_AUDIO)) {
                    c = 0;
                    break;
                }
                break;
            case 112202875:
                if (str.equals(ZFYMediaManager.ACTION_VIDEO)) {
                    c = 1;
                    break;
                }
                break;
            case 793484836:
                if (str.equals(ZFYMediaManager.KNOCK_PROTECT)) {
                    c = 2;
                    break;
                }
                break;
        }
        switch (c) {
            case 0:
                Log.i(TAG, "ACTION_AUDIO");
                if (ZFYMediaManager.getInstance().getStatus().isWaitAudioNote()) {
                    Log.i(TAG, "ACTION_AUDIO_NOTE_START");
                    this.actionStack.add(ZFYMediaManager.ACTION_AUDIO_NOTE_START);
                    ZFYMediaManager.getInstance().getStatus().setWaitAudioNote(false);
                    break;
                } else if (ZFYMediaManager.getInstance().getStatus().isAudioNote()) {
                    this.actionStack.add(ZFYMediaManager.ACTION_AUDIO_NOTE_STOP);
                    break;
                } else if (ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
                    this.actionStack.add(ZFYMediaManager.ACTION_AUDIO_STOP);
                    break;
                } else {
                    if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
                        this.actionStack.add(ZFYMediaManager.ACTION_VIDEO_STOP);
                    }
                    this.actionStack.add(ZFYMediaManager.ACTION_AUDIO_START);
                    break;
                }
            case 1:
                if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
                    if (ZFYMediaManager.getInstance().getConfig().getVideoDelayTime() > 0) {
                        this.actionStack.add(ZFYMediaManager.ACTION_VIDEO_DELAY_STOP);
                        break;
                    } else {
                        this.actionStack.add(ZFYMediaManager.ACTION_VIDEO_STOP);
                        break;
                    }
                } else {
                    if (ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
                        this.actionStack.add(ZFYMediaManager.ACTION_AUDIO_STOP);
                    }
                    this.actionStack.add(ZFYMediaManager.ACTION_VIDEO_START);
                    break;
                }
            case 2:
                if (!ZFYMediaManager.getInstance().getStatus().isVideoStart() || !ZFYMediaManager.getInstance().getStatus().isRemoteVideoAndAudio() || !ZFYMediaManager.getInstance().getStatus().isDelayRecording()) {
                    this.actionStack.add(ZFYMediaManager.ACTION_VIDEO_START);
                    this.actionStack.add(ZFYMediaManager.ACTION_MARK);
                    break;
                }
                break;
            default:
                if (!str.equalsIgnoreCase(this.actionStack.peek())) {
                    this.actionStack.add(str);
                    break;
                }
                break;
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = this.actionStack.iterator();
        while (it.hasNext()) {
            sb.append(" " + it.next());
        }
        Log.d(TAG, "action stack:" + ((Object) sb));
        if (z) {
            nextAction();
        }
    }

    public synchronized void nextAction() {
        if (this.nextActionDisposable != null) {
            Log.w(TAG, "nextAction nextActionDisposable != null");
        } else {
            Observable.just(Boolean.TRUE).flatMap(new Function() {
                @Override
                public  Object apply(Object obj) {
                    return PreviewBusinessController.this.m600x71b802c((Boolean) obj);
                }
            }).repeat().doFinally(new Action() {
                @Override
                public void run() {
                    PreviewBusinessController.this.m601x7e9fead();
                }
            }).subscribe(new Observer<Boolean>() {
                @Override
                public void onNext(Boolean bool) {
                }

                @Override
                public void onSubscribe(Disposable disposable) {
                    PreviewBusinessController.this.nextActionDisposable = disposable;
                }

                @Override
                public void onError(Throwable th) {
                    onComplete();
                }

                @Override
                public void onComplete() {
                    ZFYMediaStatus status = ZFYMediaManager.getInstance().getStatus();
                    PreviewBusinessController.this.needRecordingTime = (status.isVideoStart() && !status.isDelayRecording()) || status.isAudioStart();
                    Log.i(TAG, "refreshRecording needRecordingTime " + PreviewBusinessController.this.needRecordingTime);
                    PreviewBusinessController.this.previewViewModel.refreshRecordingAction();
                }
            });
        }
    }

    public  ObservableSource m600x71b802c(Boolean bool){
        Single<Boolean> nextAction = getNextAction();
        if (nextAction == null) {
            nextAction = Single.error(new Throwable("no getNextAction"));
        }
        return nextAction.toObservable();
    }

    public  void m601x7e9fead(){
        Log.d(TAG, "doFinally nextActionDisposable = null");
        this.nextActionDisposable = null;
    }

    private Single<Boolean> getNextAction() {
        Single<Boolean> startRemoteAudioAction = null;
        String poll = this.actionStack.poll();
        if (poll == null) {
            Log.d(TAG, "action = null all stoped");
            return null;
        }
        Log.d(TAG, "nextAction " + poll);
        poll.hashCode();
        char c = 65535;
        switch (poll.hashCode()) {
            case -2096238800:
                if (poll.equals(ZFYMediaManager.ACTION_REMOTE_AUDIO)) {
                    c = 0;
                    break;
                }
                break;
            case -2077202475:
                if (poll.equals(ZFYMediaManager.ACTION_REMOTE_VIDEO)) {
                    c = 1;
                    break;
                }
                break;
            case -1736595804:
                if (poll.equals(ZFYMediaManager.ACTION_GROUPINTERCOM)) {
                    c = 2;
                    break;
                }
                break;
            case -1645537990:
                if (poll.equals(ZFYMediaManager.CHANGE_PPI)) {
                    c = 3;
                    break;
                }
                break;
            case -1617870522:
                if (poll.equals(ZFYMediaManager.ACTION_VIDEO_STOP)) {
                    c = 4;
                    break;
                }
                break;
            case -1478990881:
                if (poll.equals(ZFYMediaManager.ACTION_PRE_VIDEO)) {
                    c = 5;
                    break;
                }
                break;
            case -1435260780:
                if (poll.equals(ZFYMediaManager.ACTION_USB_CHANGE)) {
                    c = 6;
                    break;
                }
                break;
            case -1236116832:
                if (poll.equals(ZFYMediaManager.ACTION_AI_PREVIEW)) {
                    c = 7;
                    break;
                }
                break;
            case -1225074612:
                if (poll.equals(ZFYMediaManager.CHANGE_MEDIA_CONFIG)) {
                    c = '\b';
                    break;
                }
                break;
            case -1147007425:
                if (poll.equals(ZFYMediaManager.PAUSE_PREVIEW)) {
                    c = '\t';
                    break;
                }
                break;
            case 3344077:
                if (poll.equals(ZFYMediaManager.ACTION_MARK)) {
                    c = '\n';
                    break;
                }
                break;
            case 93166550:
                if (poll.equals(ZFYMediaManager.ACTION_AUDIO)) {
                    c = 11;
                    break;
                }
                break;
            case 112202875:
                if (poll.equals(ZFYMediaManager.ACTION_VIDEO)) {
                    c = '\f';
                    break;
                }
                break;
            case 160543198:
                if (poll.equals(ZFYMediaManager.ACTION_AUDIO_NOTE_START)) {
                    c = '\r';
                    break;
                }
                break;
            case 249016213:
                if (poll.equals(ZFYMediaManager.ACTION_CHANGE_WIDE_ANGLE_DISTORTION)) {
                    c = 14;
                    break;
                }
                break;
            case 382774856:
                if (poll.equals(ZFYMediaManager.ACTION_START_FACE_DETECT)) {
                    c = 15;
                    break;
                }
                break;
            case 474323659:
                if (poll.equals(ZFYMediaManager.VIDEO_PROTECT)) {
                    c = 16;
                    break;
                }
                break;
            case 516709177:
                if (poll.equals(ZFYMediaManager.ACTION_RESET_PPI)) {
                    c = 17;
                    break;
                }
                break;
            case 552582240:
                if (poll.equals(ZFYMediaManager.ACTION_CAPTRUE)) {
                    c = 18;
                    break;
                }
                break;
            case 610931387:
                if (poll.equals(ZFYMediaManager.ACTION_START_QRSCAN)) {
                    c = 19;
                    break;
                }
                break;
            case 784992953:
                if (poll.equals(ZFYMediaManager.ACTION_AUDIO_START)) {
                    c = 20;
                    break;
                }
                break;
            case 859144363:
                if (poll.equals(ZFYMediaManager.START_PREVIEW)) {
                    c = 21;
                    break;
                }
                break;
            case 975010566:
                if (poll.equals(ZFYMediaManager.ACTION_AUDIO_NOTE_STOP)) {
                    c = 22;
                    break;
                }
                break;
            case 1277566745:
                if (poll.equals(ZFYMediaManager.ACTION_CHANGE_MEDIA_CONFIG_FROM_PLATFORM)) {
                    c = 23;
                    break;
                }
                break;
            case 1385608094:
                if (poll.equals(ZFYMediaManager.ACTION_VIDEO_START)) {
                    c = 24;
                    break;
                }
                break;
            case 1506755080:
                if (poll.equals(ZFYMediaManager.ACTION_STOP_FACE_DETECT)) {
                    c = 25;
                    break;
                }
                break;
            case 1532683776:
                if (poll.equals(ZFYMediaManager.LEAVE_PREVIEW)) {
                    c = 26;
                    break;
                }
                break;
            case 1549343435:
                if (poll.equals(ZFYMediaManager.ACTION_AUDIO_STOP)) {
                    c = 27;
                    break;
                }
                break;
            case 1565177730:
                if (poll.equals(ZFYMediaManager.ACTION_VIDEO_DELAY_STOP)) {
                    c = 28;
                    break;
                }
                break;
            case 1715804161:
                if (poll.equals(ZFYMediaManager.ACTION_CAPTRUE_WITH_CONFIG)) {
                    c = 29;
                    break;
                }
                break;
            case 1816730632:
                if (poll.equals(ZFYMediaManager.ACTION_SYNC_TIME)) {
                    c = 30;
                    break;
                }
                break;
            case 2027934321:
                if (poll.equals(ZFYMediaManager.ACTION_CHECK_AUDIO_MODE)) {
                    c = 31;
                    break;
                }
                break;
        }
        switch (c) {
            case 0:
                startRemoteAudioAction = startRemoteAudioAction();
                break;
            case 1:
                startRemoteAudioAction = startRemoteVideoAction();
                break;
            case 2:
                startRemoteAudioAction = startGroupintercomVideo();
                break;
            case 3:
                startRemoteAudioAction = changePPIAction();
                break;
            case 4:
                startRemoteAudioAction = stopVideoAction();
                break;
            case 5:
                if (ZFYMediaManager.getInstance().getStatus().isPreRecording()) {
                    startRemoteAudioAction = stopPreVideoAction();
                    break;
                } else {
                    startRemoteAudioAction = startPreVideoAction();
                    break;
                }
            case 6:
                startRemoteAudioAction = checkWhenUSBChange();
                break;
            case 7:
                startRemoteAudioAction = checkAIPreview();
                break;
            case '\b':
                startRemoteAudioAction = changeMediaConfig();
                break;
            case '\t':
                startRemoteAudioAction = onPauseAction();
                break;
            case '\n':
                startRemoteAudioAction = ZFYMediaManager.getInstance().markImportant().delay(1L, TimeUnit.SECONDS);
                break;
            case 11:
                if (ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
                    startRemoteAudioAction = stopAudioRecordAction();
                    break;
                } else {
                    startRemoteAudioAction = startAudioRecordAction();
                    break;
                }
            case '\f':
                if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
                    startRemoteAudioAction = stopVideoAction();
                    break;
                } else {
                    startRemoteAudioAction = startVideoAction();
                    break;
                }
            case '\r':
                //开始音频标记
                break;
            case 14:
                startRemoteAudioAction = changeWideAngleDistortion();
                break;
            case 15:
                //开始人脸识别
                break;
            case 16:
                startRemoteAudioAction = videoProtect();
                break;
            case 17:
                startRemoteAudioAction = resetPPIAction();
                break;
            case 18:
                startRemoteAudioAction = capture();
                break;
            case 19:
                //startRemoteAudioAction = startQRScan();
                break;
            case 20:
                startRemoteAudioAction = startAudioRecordAction();
                break;
            case 21:
                startRemoteAudioAction = onResumeAction();
                break;
            case 22:
                //停止音频标记
                break;
            case 23:
                //前置选择平台媒体参数
                break;
            case 24:
                startRemoteAudioAction = startVideoAction();
                break;
            case 25:
                //停止人脸检索
                break;
            case 26:
                startRemoteAudioAction = leavePreview();
                break;
            case 27:
                startRemoteAudioAction = stopAudioRecordAction();
                break;
            case 28:
                startRemoteAudioAction = delayStopVideoAction();
                break;
            case 29:
                startRemoteAudioAction = captureWithConfig();
                break;
            case 30:
                startRemoteAudioAction = ZFYMediaManager.getInstance().cacheSyncDevTime();
                break;
            case 31:
                startRemoteAudioAction = checkAudioCommunicationMode();
                break;
            default:
                startRemoteAudioAction = null;
                break;
        }
        if (startRemoteAudioAction == null) {
            Log.w(TAG, "mediaActionSingle == null");
            return null;
        }
        return startRemoteAudioAction.doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
            }
        }).timeout(5L, TimeUnit.SECONDS).doOnError(new Consumer() {
            @Override
            public void accept(Object obj) {
                ((Throwable) obj).printStackTrace();
            }
        }).onErrorReturnItem(Boolean.FALSE);
    }

    public void updateCameraStream(boolean z, boolean z2, boolean z3) {
        if (z3 || ZFYMediaManager.getInstance().getStatus().isForceCloseWideAngleDistortion()) {
            Log.i(TAG, "setWideAngleDistortion false");
            getCameraViewModel().setWideAngleDistortion(false);
        } else {
            Log.i(TAG, "setWideAngleDistortion else " + (ZFYMediaManager.getInstance().getConfig().getWideAngleDistortion() != 1));
            getCameraViewModel().setWideAngleDistortion(ZFYMediaManager.getInstance().getConfig().getWideAngleDistortion() != 1);
        }
        getCameraViewModel().updateCameraStream(z, z2, z3);
    }

    private Single<Boolean> onResumeAction() {
        Log.i(TAG, "onResumeAction");
        this.foregroundDisposable = new CompositeDisposable();
        return firstInstall().flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return authFirstInit();
            }
        }).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                if (ZFYMediaManager.getInstance().isNeedVideoStream() && videoDataSource == null) {
                    Log.w(TAG, "videoDataSource == null");
                    videoDataSource = ZFYMediaManager.getInstance().getVideoDataSource();
                }
                if (ZFYMediaManager.getInstance().isNeedRemoteStream() && remoteVideoDataSource == null) {
                    Log.w(TAG, "remoteVideoDataSource == null");
                    remoteVideoDataSource = ZFYMediaManager.getInstance().getRemoteVideoDataSource();
                }
                return Boolean.TRUE;
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return updateCameraStream();
            }
        }).delay(300L, TimeUnit.MILLISECONDS).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                if (statusViewModel != null) {
                    statusViewModel.onResume();
                }
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getSensorViewModel().onResume();
                if (isLeave.get()) {
                    onBackPreview();
                }
                refreshStorageSize();
                refreshStaticData();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                resumeOrPauseStatus = true;
            }
        }).flatMap(new Function<Boolean, SingleSource<Boolean>>() {
            @Override
            public SingleSource<Boolean> apply(Boolean bool) throws Exception {
                Log.i(TAG, "onResumeAction checkAIPreview actionStack " + PreviewBusinessController.this.actionStack.size());
                return checkAIPreview();
            }
        }).onErrorReturnItem(Boolean.FALSE);
    }



    private Single<Boolean> onPauseAction() {
        if (this.isForeground.get()) {
            return Single.just(Boolean.FALSE);
        }
        return Single.just(Boolean.TRUE).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return PreviewBusinessController.this.m607xef446641((Boolean) obj);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return PreviewBusinessController.this.m608xf012e4c2((Boolean) obj);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return PreviewBusinessController.this.m609x1d1c3d8((Boolean) obj);
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                PreviewBusinessController.this.m610x2a04259((Boolean) obj);
            }
        });
    }

    public  SingleSource m607xef446641(Boolean bool){
        this.statusViewModel.onPause();
        CompositeDisposable compositeDisposable = this.foregroundDisposable;
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            this.foregroundDisposable = null;
        }
        getSensorViewModel().onPause();
        Log.i(TAG, "onPauseAction");
        if (ZFYMediaManager.getInstance().isNeedVideoStream() || ZFYMediaManager.getInstance().isNeedRemoteStream()) {
            updateCameraStream(false, ZFYMediaManager.getInstance().isNeedVideoStream(), ZFYMediaManager.getInstance().isNeedRemoteStream());
            return Single.just(Boolean.TRUE);
        }
        return pauseCameraAndSurface();
    }

    public  SingleSource m608xf012e4c2(Boolean bool) {
        return this.frontCameraRecordingViewModel.onPauseAction();
    }

    public SingleSource m609x1d1c3d8(Boolean bool) {
        return checkAIPreview();
    }

    public void m610x2a04259(Boolean bool){
        this.resumeOrPauseStatus = false;
    }

    private Single<Boolean> updateCameraStream() {
        return Single.zip(Single.just(Boolean.valueOf(this.isForeground.get())), resumeCamera(), new BiFunction() {
            @Override
            public  Object apply(Object obj, Object obj2) {
                return Single.just(Boolean.TRUE);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                Boolean bool = (Boolean) obj;
                if (!bool.booleanValue() && cameraViewModel.useEGLPreviewSurface())
                {
                    return Single.just(true).doOnSuccess(new Consumer() {
                        @Override
                        public  void accept(Object obj) {
                            ZFYMediaManager.getInstance().wakeScreen();
                        }
                    }).flatMap(new Function() {
                        @Override
                        public  Object apply(Object obj) {
                            return setUpSurface();
                        }
                    });
                }
                if (!bool.booleanValue()) {
                    return Single.just(false);
                }
                return setUpSurface();
            }
        }).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                Boolean bool = (Boolean) obj;
                updateCameraStream(bool.booleanValue(), ZFYMediaManager.getInstance().isNeedVideoStream(), ZFYMediaManager.getInstance().isNeedRemoteStream());
                return Boolean.TRUE;
            }
        });
    }

    private Single<Boolean> checkWhenUSBChange() {
        return Single.timer(LONE_PRESS_TIME, TimeUnit.MILLISECONDS).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return checkAIPreview();
            }
        });
    }


    private Single<Boolean> videoProtect() {
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                BeepTool.play(BeepType.PRE_MARKED);
                BeepTool.play(BeepType.VIDEO_STOP);
                BeepTool.play(BeepType.VIDEO_START);
                BeepTool.play(BeepType.PRE_MARKED);
                ZFYMediaManager.getInstance().getStatus().setImportant(2);
                ZFYMediaManager.getInstance().forceSwitchVideo();
            }
        });
    }


    private Single<Boolean> leavePreview() {
        return checkLeaveStatus().flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return leaveAction();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                if (ZFYMediaManager.getInstance().getLeaveActionSubject() != null) {
                    ZFYMediaManager.getInstance().getLeaveActionSubject().onNext((Boolean) obj);
                }
                if (captureDisposable != null) {
                    captureDisposable.dispose();
                    captureDisposable = null;
                }
            }
        }).doOnError(new Consumer() {
            @Override
            public  void accept(Object obj) {
                if (ZFYMediaManager.getInstance().getLeaveActionSubject() != null) {
                    ZFYMediaManager.getInstance().getLeaveActionSubject().onError((Throwable) obj);
                }
                if (captureDisposable != null) {
                    captureDisposable.dispose();
                    captureDisposable = null;
                }
            }
        });
    }

    private Single<Boolean> checkAudioCommunicationMode() {
        return Single.just(Boolean.TRUE).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                return PreviewBusinessController.this.m570x3a9d2ddf((Boolean) obj);
            }
        });
    }

    public  Boolean m570x3a9d2ddf(Boolean bool) {
        if (this.audioRecord == null) {
            return Boolean.TRUE;
        }
        this.audioRecord.changeMode(ZFYMediaManager.getInstance().getStatus().isNeedCommuniMode() ? 1 : 0);
        return Boolean.FALSE;
    }

    private Single<IGSNV12DataSource> createVideoDataSource() {
        if (this.videoDataSource != null) {
            Log.w(TAG, "videoDataSource != null");
            return Single.just(this.videoDataSource);
        }
        Log.i(TAG, "createVideoDataSource");
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                Log.i(TAG, "createVideoDataSource success");
            }
        }).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return updateCameraStream();
            }
        }).map(new Function() {
            @Override
            public Object apply(Object obj) {
                ZFYCameraParameters cameraParameters = getCameraViewModel().getCameraParameters();
                Log.i(TAG, "createVideoDataSource " + cameraParameters.getVideoWidth() + " x " + cameraParameters.getVideoHeight());
                GSNV12OSDDataSource gSNV12OSDDataSource = new GSNV12OSDDataSource(cameraParameters.getVideoWidth(), cameraParameters.getVideoHeight(), cameraParameters.getVideoFps());
                gSNV12OSDDataSource.addObserver(videoDataSourceObserver);
                return gSNV12OSDDataSource;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                IGSNV12DataSource iGSNV12DataSource = (IGSNV12DataSource) obj;
                videoDataSource = iGSNV12DataSource;
                if (previewSurfaceTextureHelper != null) {
                    previewSurfaceTextureHelper.setVideoDataSource(iGSNV12DataSource);
                } else {
                    Log.e(TAG, "previewSurfaceTextureHelper == null");
                }
            }
        });
    }

    private Single<IGSNV12DataSource> createRemoteVideoDataSource() {
        if (!ZFYMediaManager.getInstance().getConfig().isDualStream()) {
            return createVideoDataSource();
        }
        return updateCameraStream().map(new Function() {
            @Override
            public  Object apply(Object obj) {
                ZFYCameraParameters cameraParameters = getCameraViewModel().getCameraParameters();
                Log.i(TAG, "createRemoteVideoDataSource " + cameraParameters.getRemoteWidth() + " x " + cameraParameters.getRemoteHeight() + " x " + cameraParameters.getRemoteFps());
                GSNV12OSDDataSource gSNV12OSDDataSource = new GSNV12OSDDataSource(cameraParameters.getRemoteWidth(), cameraParameters.getRemoteHeight(), cameraParameters.getRemoteFps());
                gSNV12OSDDataSource.addObserver(remoteVideoDataSourceObserver);
                return gSNV12OSDDataSource;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                IGSNV12DataSource iGSNV12DataSource = (IGSNV12DataSource) obj;
                remoteVideoDataSource = iGSNV12DataSource;
                if (previewSurfaceTextureHelper != null) {
                    previewSurfaceTextureHelper.setRemoteVideoDataSource(iGSNV12DataSource);
                }
            }
        });
    }


    private Single<Boolean> startVideoAction() {
        if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
            Log.i(TAG, "startVideoAction isVideoStart");
            return Single.just(Boolean.TRUE);
        }
        return ZFYMediaManager.getInstance().startVideoAction(createVideoDataSource(), createAudioAction()).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                PreviewBusinessController.this.m634x7776aa5f((Boolean) obj);
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return frontCameraRecordingViewModel.startVideoAction();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return checkAIPreview();
            }
        }).delay(4L, TimeUnit.SECONDS);
    }

    public  void m634x7776aa5f(Boolean bool){
        this.needRecordingTime = true;
        this.previewViewModel.refreshRecordingAction();
        showToast(getString(R.string.meida_start_video));
        getSensorViewModel().onVideoStart();
        PlatformProxy.getInstance().reportAction("postStatusReport", "RECORDING");
        if (ZFYMediaManager.getInstance().getConfig().getWideAngleDistortion() == 0) {
            delayCloseWideAngleDistortion();
        }
    }

    private Single<Boolean> stopVideoAction() {
        if (!ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
            return Single.just(Boolean.TRUE);
        }
        cancleCloseWideAngleDistortion();
        return ZFYMediaManager.getInstance().stopVideoAction().doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getSensorViewModel().onVideoStop();
            }
        }).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return frontCameraRecordingViewModel.stopVideoAction();
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                showToast(getString(R.string.meida_recording_save_complete));
                PlatformProxy.getInstance().reportAction("postStatusReport", "RECORDING_FINISHED");
            }
        }).delay(500L, TimeUnit.MILLISECONDS).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return checkAIPreview();
            }
        });
    }


    private Single<Boolean> delayStopVideoAction() {
        if (!ZFYMediaManager.getInstance().getStatus().isVideoStart() || ZFYMediaManager.getInstance().getStatus().isDelayRecording()) {
            showToast(getString(R.string.preview_delay_recording));
            return Single.just(Boolean.TRUE);
        }
        int videoDelayTime = ZFYMediaManager.getInstance().getConfig().getVideoDelayTime();
        Log.i(TAG, "delayStopVideoAction " + videoDelayTime);
        if (videoDelayTime > 0) {
            BeepTool.play(BeepType.VIDEO_DELAY_STOP);
            ZFYMediaManager.getInstance().getStatus().setDlayRecording(true);
            Log.i(TAG, "delay end Recording " + videoDelayTime);
            this.previewViewModel.refreshRecordingAction();
            Disposable disposable = this.delayStopVideoActionDisposable;
            if (disposable != null) {
                disposable.dispose();
                this.delayStopVideoActionDisposable = null;
            }
            Single.just(Boolean.TRUE).delay(videoDelayTime, TimeUnit.SECONDS).subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onError(Throwable th) {
                }

                @Override
                public void onSubscribe(Disposable disposable2) {
                    PreviewBusinessController.this.delayStopVideoActionDisposable = disposable2;
                }

                @Override
                public void onSuccess(Boolean bool) {
                    Log.i(PreviewBusinessController.TAG, "delayStopVideoAction onSuccess");
                    if (ZFYMediaManager.getInstance().getStatus().isDelayRecording()) {
                        PreviewBusinessController.this.handleMediaAction(ZFYMediaManager.ACTION_VIDEO_STOP);
                    }
                }
            });
        }
        return Single.just(Boolean.TRUE);
    }

    private Single<Boolean> startPreVideoAction() {
        return ZFYMediaManager.getInstance().startPreVideoAction(createVideoDataSource(), createAudioAction());
    }

    private Single<Boolean> stopPreVideoAction() {
        return ZFYMediaManager.getInstance().stopPreVideoAction();
    }

    public Single<Boolean> checkAIPreview() {
        return Single.just(Boolean.FALSE);
    }

    private Single<Boolean> startAudioRecordAction() {
        if (ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
            return Single.just(Boolean.TRUE);
        }
        return ZFYMediaManager.getInstance().startAudioRecordAction(createAudioAction()).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                needRecordingTime = true;
                showToast(getString(R.string.meida_start_audio));
                getSensorViewModel().onAudioStart();
            }
        });
    }


    private Single<Boolean> stopAudioRecordAction() {
        if (!ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
            return Single.just(Boolean.TRUE);
        }
        return ZFYMediaManager.getInstance().stopAudioRecordAction().doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getSensorViewModel().onAudioStop();
                showToast(getString(R.string.meida_stop_audio));
            }
        });
    }


    private Single<Boolean> startRemoteVideoAction() {
        if (ZFYMediaManager.getInstance().getConfig().isDualStream()) {
            if (ZFYMediaManager.getInstance().getConfig().isFrontCameraStream()) {
                return ZFYMediaManager.getInstance().startRemoteVideoAction(this.frontCameraRecordingViewModel.createRemoteDataSource(), createAudioAction());
            }
            return ZFYMediaManager.getInstance().startRemoteVideoAction(createRemoteVideoDataSource(), createAudioAction());
        }
        return ZFYMediaManager.getInstance().startRemoteVideoAction(createVideoDataSource(), createAudioAction());
    }

    private Single<Boolean> startRemoteAudioAction() {
        return ZFYMediaManager.getInstance().startRemoteAudioAction(createAudioAction());
    }

    private Single<Boolean> startGroupintercomVideo() {
        if (ZFYMediaManager.getInstance().getConfig().isDualStream()) {
            return ZFYMediaManager.getInstance().startGroupintercomVideo(createRemoteVideoDataSource(), createAudioAction());
        }
        return ZFYMediaManager.getInstance().startGroupintercomVideo(createVideoDataSource(), createAudioAction());
    }

    public synchronized Single<IGSWAVDataSource> createAudioAction() {
        Single map;
        Log.w(TAG, "creatWavDataSource");
        if (this.audioRecord != null) {
            map = Single.just(this.audioRecord);
        } else {
            map = Single.just(Boolean.TRUE).map(new Function() {
                @Override
                public  Object apply(Object obj) {
                    GSWAVDataSource gSWAVDataSource = new GSWAVDataSource(ZFYMediaManager.getInstance().getStatus().isNeedCommuniMode() ? 1 : 0, getContext());
                    gSWAVDataSource.addObserver(audioDataSourceObserver);
                    return gSWAVDataSource;
                }
            });
        }
        return map.doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                ((GSWAVDataSource) obj).startRecord();
                audioRecord = (GSWAVDataSource) obj;
            }
        }).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                return (GSWAVDataSource) obj;
            }
        });
    }

    private FragmentManager getSupportFragmentManager() {
        return this.activityWeakReference.get().getSupportFragmentManager();
    }

    public boolean isOpenedCamera() {
        return getCameraViewModel().isOpenedCamera();
    }

    public void cameraZoomPercent(float zoom) {
        getCameraViewModel().cameraZoomPercent(zoom).subscribe(new SingleObserver<Float>() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Float f2) {
            }

            @Override
            public void onError(Throwable th) {
                PreviewBusinessController.this.showToast(th.getMessage());
            }
        });
    }


    //检测返回状态
    private Single<Boolean> checkLeaveStatus() {
        Log.i(TAG, "checkLeaveStatus");
        if (ZFYMediaManager.getInstance().getStatus().isRemoteVideoAndAudio()) {
            return Single.error(new Throwable(getString(R.string.meida_error_status_remoting)));
        }
        if (ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
            return Single.error(new Throwable(getString(R.string.meida_error_status_recording)));
        }
        if (ZFYMediaManager.getInstance().getStatus().isAudioStart()) {
            return Single.error(new Throwable(getString(R.string.meida_error_status_audio_recording)));
        }
        if (ZFYMediaManager.getInstance().getStatus().isDelayRecording()) {
            return Single.error(new Throwable(getString(R.string.preview_delay_recording)));
        }
        if (ZFYMediaManager.getInstance().getStatus().isRemoteOnlyAudio()) {
            return Single.error(new Throwable(getString(R.string.meida_remote_audio_leave)));
        }
        if (ZFYMediaManager.getInstance().getStatus().isGroupintercomVideo()) {
            return Single.error(new Throwable(getString(R.string.meida_error_status_groupintercom_videomeeting)));
        }
        if (getCameraViewModel().isLocked()) {
            Log.i(TAG, "camera.isLocked()");
            return Single.error(new Throwable(getString(R.string.please_wait)));
        }
        return Single.just(Boolean.TRUE);
    }

    private void onBackPreview() {
        ZFYMediaManager.getInstance().onBackPreview(getContext());
        subscribeRxBus();
        this.isLeave.set(false);
    }

    private Single<Boolean> changeWideAngleDistortion() {
        if (!ZFYMediaManager.getInstance().isNeedRemoteStream() && !ZFYMediaManager.getInstance().isNeedVideoStream()) {
            return Single.just(Boolean.FALSE);
        }
        return Single.just(Boolean.TRUE).flatMap(new Function() {
            @Override
            public Object apply(Object obj) {
                return PreviewBusinessController.this.m569x92cda790((Boolean) obj);
            }
        });
    }

    public  SingleSource m569x92cda790(Boolean bool){
        Log.i(TAG, "setForceCloseWideAngleDistortion true");
        ZFYMediaManager.getInstance().getStatus().setForceCloseWideAngleDistortion(true);
        getCameraViewModel().setWideAngleDistortion(false);
        Log.i(TAG, "startPreviewStream");
        return getCameraViewModel().startPreviewStream();
    }

    private void delayCloseWideAngleDistortion() {
        if (this.delayCloseWideAngleDisposable != null) {
            return;
        }
        Log.i(TAG, "delayCloseWideAngleDistortion");
        Single.just(Boolean.TRUE).delay(15L, TimeUnit.MINUTES).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                Log.i(TAG, "handlerActionWithCheckForground ACTION_CHANGE_WIDE_ANGLE_DISTORTION");
                BeepTool.beepOneShot();
                ZFYMediaManager.getInstance().handlerActionWithCheckForground(getContext(), ZFYMediaManager.ACTION_CHANGE_WIDE_ANGLE_DISTORTION);
            }
        }).doFinally(new Action() {
            @Override
            public void run() {
                Log.i(TAG, "delayCloseWideAngleDistortion doFinally");
                delayCloseWideAngleDisposable = null;
            }
        }).subscribe(new SingleObserver<Boolean>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSuccess(Boolean bool) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                PreviewBusinessController.this.delayCloseWideAngleDisposable = disposable;
            }
        });
    }

    private void cancleCloseWideAngleDistortion() {
        Log.i(TAG, "cancleCloseWideAngleDistortion setForceCloseWideAngleDistortion false");
        ZFYMediaManager.getInstance().getStatus().setForceCloseWideAngleDistortion(false);
        if (delayCloseWideAngleDisposable != null) {
            delayCloseWideAngleDisposable.dispose();
            delayCloseWideAngleDisposable = null;
        }
    }


    //设置系统时区和息屏时间
    private Single<Boolean> resetSystem() {
        return Single.just(Boolean.TRUE).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                try {
                    Settings.Global.putInt(getContext().getContentResolver(), "auto_time_zone", 0);
                    ((AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE)).setTimeZone("Asia/Shanghai");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Uri uriFor = Settings.System.getUriFor("screen_off_timeout");
                try {
                    if (Settings.System.putLong(ClientApp.clientApp.getApplicationContext().getContentResolver(), "screen_off_timeout", 10000L)) {
                        getContext().getContentResolver().notifyChange(uriFor, null);
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return Boolean.TRUE;
            }
        }).onErrorReturnItem(Boolean.FALSE);
    }

}
